/*
 * @Author: Wxx
 * @Date: 2022-02-26 16:35:11
 * @LastEditors: Wxx
 * @LastEditTime: 2022-02-26 16:42:50
 * @Description:
 */
import React, { useState, useEffect, useMemo } from "react";
import store from "../redux/store";
import { saveCinemasList } from "../redux/actionCreator/CinemasCreator";
export default function Search() {
  const [cinemasList, setCinemasList] = useState(
    store.getState().Cinemas.cinemasList
  );
  const [text, setText] = useState("");

  useEffect(() => {
    if (store.getState().Cinemas.cinemasList.length === 0) {
      store.dispatch(saveCinemasList());
    } else {
      console.log("缓存");
    }
    var unsubscribe = store.subscribe(() => {
      setCinemasList(store.getState().Cinemas.cinemasList);
    });
    return () => {
      unsubscribe();
    };
  }, []);

  const handleChange = (e) => {
    setText(e.target.value);
  };

  // 类似于vue中的计算属性
  const getFilterList = useMemo(
    () =>
      cinemasList.filter(
        (item) =>
          item.name.toUpperCase().includes(text.toUpperCase()) ||
          item.address.toUpperCase().includes(text.toUpperCase())
      ),
    [cinemasList, text]
  );
  return (
    <div>
      <input
        style={{ width: "100%", height: 40 }}
        placeholder="输入关键字进行搜索"
        value={text}
        onChange={handleChange}
      />
      {getFilterList.map((item) => (
        <div key={item.cinemaId} style={{ borderBottom: "1px solid #eee" }}>
          <h4>{item.name}</h4>
          <p style={{ fontSize: 12 }}>{item.address}</p>
        </div>
      ))}
    </div>
  );
}
